from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
from datetime import datetime

router = APIRouter(prefix="/chart")


# 数据模型
class ChartData(BaseModel):
    labels: List[str]
    datasets: List[Dict[str, Any]]


class ChartResponse(BaseModel):
    success: bool
    data: ChartData
    message: str
    timestamp: datetime


# Mock数据 - 图表数据
chart_data = {
    "aqi_trend": {
        "labels": ["1月11日", "1月12日", "1月13日", "1月14日", "1月15日", "1月16日", "1月17日"],
        "datasets": [
            {
                "label": "AQI指数",
                "data": [58, 73, 68, 52, 45, 62, 55],
                "borderColor": "rgb(99, 102, 241)",
                "backgroundColor": "rgba(99, 102, 241, 0.3)",
                "borderWidth": 3,
                "tension": 0.4,
                "fill": True,
                "pointBackgroundColor": "rgb(99, 102, 241)",
                "pointBorderColor": "#fff",
                "pointBorderWidth": 2,
                "pointRadius": 6,
                "pointHoverRadius": 8
            }
        ]
    },
    "ozone_trend": {
        "labels": ["1月11日", "1月12日", "1月13日", "1月14日", "1月15日", "1月16日", "1月17日"],
        "datasets": [
            {
                "label": "臭氧浓度",
                "data": [85, 92, 78, 88, 95, 82, 90],
                "borderColor": "rgb(34, 197, 94)",
                "backgroundColor": "rgba(34, 197, 94, 0.3)",
                "borderWidth": 3,
                "tension": 0.4,
                "fill": True,
                "pointBackgroundColor": "rgb(34, 197, 94)",
                "pointBorderColor": "#fff",
                "pointBorderWidth": 2,
                "pointRadius": 6,
                "pointHoverRadius": 8
            }
        ]
    }
}


@router.get("/data/{chart_type}", response_model=ChartResponse)
async def get_chart_data(chart_type: str):
    """获取图表数据"""
    try:
        print(f"收到图表数据请求: {chart_type}")
        if chart_type not in chart_data:
            print(f"未找到图表类型: {chart_type}")
            raise HTTPException(status_code=404, detail="未找到对应的图表数据")
        
        data = chart_data[chart_type]
        print(f"返回图表数据: {data}")
        
        return ChartResponse(
            success=True,
            data=ChartData(**data),
            message="获取图表数据成功",
            timestamp=datetime.now()
        )
    except HTTPException:
        raise
    except Exception as e:
        print(f"图表数据请求异常: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/presets")
async def get_chart_presets():
    """获取图表预设"""
    try:
        presets = {
            "aqi_trend": {
                "name": "AQI趋势图",
                "description": "空气质量指数变化趋势",
                "type": "line",
                "options": {
                    "responsive": True,
                    "maintainAspectRatio": False,
                    "plugins": {
                        "legend": {
                            "display": True,
                            "position": "top"
                        }
                    },
                    "scales": {
                        "y": {
                            "beginAtZero": True,
                            "max": 100,
                            "title": {
                                "display": True,
                                "text": "AQI指数"
                            }
                        },
                        "x": {
                            "title": {
                                "display": True,
                                "text": "日期"
                            }
                        }
                    }
                }
            },
            "ozone_trend": {
                "name": "臭氧趋势图",
                "description": "臭氧浓度变化趋势",
                "type": "line",
                "options": {
                    "responsive": True,
                    "maintainAspectRatio": False,
                    "plugins": {
                        "legend": {
                            "display": True,
                            "position": "top"
                        }
                    },
                    "scales": {
                        "y": {
                            "beginAtZero": True,
                            "title": {
                                "display": True,
                                "text": "臭氧浓度"
                            }
                        },
                        "x": {
                            "title": {
                                "display": True,
                                "text": "日期"
                            }
                        }
                    }
                }
            }
        }
        
        return {
            "success": True,
            "data": presets,
            "message": "获取图表预设成功",
            "timestamp": datetime.now()
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))